import { createRouter, createWebHashHistory } from "vue-router";
import { staticRouter, errorRouter } from "@/routers/modules/staticRouter.ts";
import NProgress from "@/config/nprogress.ts";
import {LOGIN_URL, ROUTER_WHITE_LIST} from "@/config";
import {initDynamicRouter} from "@/routers/modules/dynamicRouter.ts";
import {routerStore} from "@/stores/modules/router.ts";
import {authStore} from "@/stores/modules/auth.ts";

/**
 * @description 📚 路由参数配置简介
 * @param path ==> 路由菜单访问路径
 * @param name ==> 路由 name (对应页面组件 name, 可用作 KeepAlive 缓存标识 && 按钮权限筛选)
 * @param redirect ==> 路由重定向地址
 * @param component ==> 视图文件路径
 * @param meta ==> 路由菜单元信息
 * */
const router = createRouter({
    history: createWebHashHistory(),
    routes: [...staticRouter, ...errorRouter],
    strict: false,
    scrollBehavior: () => ({ left: 0, top: 0 })
});

/**
 * @description 路由拦截 beforeEach
 * */
router.beforeEach(async (to, from, next) => {

    const authState = authStore();
    const routerState = routerStore();

    // 1.NProgress 开始
    NProgress.start();

    // 2.动态设置标题
    const title = import.meta.env.VITE_GLOB_APP_TITLE;
    document.title = to.meta.title ? `${to.meta.title} - ${title}` : title;

    // 3.判断是访问登陆页，有 Token 就在当前页面，没有 Token 重置路由到登陆页
    if (to.path.toLocaleLowerCase() === LOGIN_URL) {
        if (authState.token) return next(from.fullPath);
        authState.resetAuth();
        routerState.resetRouters();
        return next();
    }

    // 4.判断访问页面是否在路由白名单地址(静态路由)中，如果存在直接放行
    if (ROUTER_WHITE_LIST.includes(to.path)) return next();

    // 5.判断是否有 Token，没有重定向到 login 页面
    if (!authState.token) {
        authState.resetAuth();
        routerState.resetRouters();
        return next({ path: LOGIN_URL, replace: true });
    }

    // 6.如果没有设置动态路由，则初始化并添加动态路由
    routerState.setRouteId(to.meta.id as string)
    routerState.setRouteName(to.name as string);
    if (!routerState.getDynamicRouteInit) {
        await initDynamicRouter();
        routerState.setDynamicRouterInit(true);
        return next({ ...to, replace: true });
    }

    // 7.正常访问页面
    return next();
});

/**
 * @description 路由跳转错误
 * */
router.onError(error => {
    NProgress.done();
    console.warn("路由错误", error.message);
});

/**
 * @description 路由跳转结束
 * */
router.afterEach((to, _from, _next) => {
    if (to.meta.keep_alive) {
        routerStore().addKeepAliveName(to.name as string);
    }
    NProgress.done();
});

export default router;
